import React, {Component} from 'react';

class BannerDemo extends Component {

    constructor(props) {
        super(props);
        this.state = {
            currentIndex: 0,
            lastIndex:-1,
            imgs: [
                'http://www.wanandroid.com/blogimgs/50c115c2-cf6c-4802-aa7b-a4334de444cd.png',
                'http://www.wanandroid.com/blogimgs/ab17e8f9-6b79-450b-8079-0f2287eb6f0f.png',
                'http://www.wanandroid.com/blogimgs/fb0ea461-e00a-482b-814f-4faca5761427.png',
                'http://www.wanandroid.com/blogimgs/62c1bd68-b5f3-4a3c-a649-7ca8c7dfabe6.png'
            ],
            timer: null,
        };

        this.toggleShow = this.toggleShow.bind(this);

    }


    toggleShow() {
        let realIndex = this.state.currentIndex;
        const currentIndex = this.state.currentIndex;
        if (currentIndex < this.state.imgs.length-1){
            realIndex +=1;
        }else {
            realIndex =0;
        }
        this.setState(() => ({
            currentIndex:realIndex,
            lastIndex: currentIndex,
        }))
    }

    componentDidMount() {
        this.state.timer = setInterval(()=>{this.toggleShow()}, 2000);
    }

    componentWillUnmount() {
        clearInterval(this.state.timer)
    }


    render() {

        return (
            <div style={rootStyle}>
                {
                    this.state.imgs.map((item, index) => {

                        let currentStyle ;
                        if (index === this.state.currentIndex){
                            currentStyle = divInsideStyle;
                        } else if (index === this.state.lastIndex){
                            currentStyle = divOutSizeStyle;
                        } else {
                            currentStyle = divCommonStyle;
                        }

                        return <div style={currentStyle} key={index}>
                            <img src={this.state.imgs[index]} style={imgStyle}/>
                        </div>;
                    })
                }
            </div>
        );
    }
}

const rootStyle = {
    width: 400,
    height: 200,
    margin: "0 auto",
    position: "relative",
    background: "orange",
    overflow:"hidden",

};

const divCommonStyle = {
    width: 400,
    height: 200,
    background: "pink",
    position: "absolute",
    transform: "translateX(400px)",
};

const imgStyle = {
    width: 400,
    height: 200,
    verticalAlign: "top",
};

const divInsideStyle = {
    width: 400,
    height: 200,
    background: "green",
    transition: "all 1s linear",
    transform: "translateX(0)",
    position: "absolute",
};

const divOutSizeStyle = {
    width: 400,
    height: 200,
    background: "yellow",
    transition: "all 1s linear",
    transform: "translateX(-400px)",
    position: "absolute",
};


export default BannerDemo;
